#include <iostream>
#include <pthread.h>
#include <string>
#include <unistd.h>
using namespace std;

//ctrl线程 控制 work线程，让它定期运行
#define NUM 3

pthread_mutex_t mtx;
pthread_cond_t cond;

void* ctrl(void* args)
{
    string name = (char*)args;
    while(true)
    {
        //pthread_cond_signal: 唤醒在条件变量下一个线程, 哪一个？
        cout << "master say : begin work..." << endl;
        pthread_cond_signal(&cond);
        //唤醒所有线程
        //pthread_cond_broadcast(&cond);
        sleep(1);

    }
}

void* work(void* args)
{
    int number = *(int*)args;
    delete (int*)args;

    while(true)
    {
        pthread_cond_wait(&cond, &mtx);
        cout << "worker: " << number << " is working..." << endl;
    }
}

int main()
{
    pthread_mutex_init(&mtx, nullptr);
    pthread_cond_init(&cond, nullptr);
    
    pthread_t master;
    pthread_t worker[NUM];

    pthread_create(&master, nullptr, ctrl, (void*)"boss");
    
    for(int i = 0; i < NUM; i++)
    {
        int* num = new int(i);
        pthread_create(worker + i, nullptr, work, (void*)num);

    }
    
    for(int i = 0; i < NUM; i++)
    {
        pthread_join(worker[i], nullptr);
    }
    
    pthread_join(master, nullptr);

    pthread_mutex_destroy(&mtx);
    pthread_cond_destroy(&cond);
    
    return 0;
}





